<?php
namespace App\Services;
use App\Models\Announcement;
use App\DTOS\Admin\AnnouncementSearchDTO;
use App\DTOS\Admin\AnnouncementInsertDTO;
use App\DTOS\Admin\AnnouncementUpdateDTO;
// 游戏公告
class AnnouncementService
{
    /**
    * @var  \Illuminate\Database\Eloquent\Builder
    */
    private Announcement $model;

    public function __construct()
    {
        $this->model = new Announcement;
    }

    public function paginate(AnnouncementSearchDTO $DTO)
    {
        $perPage = $DTO->getLimit();
        $page = $DTO->getPage();
        $model = $this->model;
        $status = $DTO->getStatus();
        $serverGroup = $DTO->getServerGroup();
        /**条件判断**/
        if (!is_null($status)){
            $now = date("Y-m-d H:i:s");
            $model = $model->whereRaw("begin_time <= '$now' && end_time >= '$now'");
        }
        if ($serverGroup) {
            if (is_string($serverGroup) && strpos($serverGroup, ',') !== false) {
                $serverGroupItems = explode(',', $serverGroup);
                $model = $model->where(function ($query) use ($serverGroupItems) {
                    foreach ($serverGroupItems as $item) {
                        $query->orWhere('serverGroup', 'LIKE', '%' . $item . '%');
                    }
                });
            } else {
                $model = $model->where('serverGroup', 'LIKE', '%' . $serverGroup . '%');
            }
        }
        return $model->orderByDesc('id')->paginate($perPage,'*','page',$page);
    }

    /**
    * @param  AnnouncementInsertDTO $insertDTO
    * @return  int
    */
    public function insert(AnnouncementInsertDTO $insertDTO){
        $data = $insertDTO->toArray();
        foreach($data as &$value){
            if (is_array($value)){
                $value= json_encode(array_values($value));
            }
        }
        $data['created_at'] = now();
        unset($data['page']);unset($data['limit']);
        return $this->model->insertGetId($data);
    }

    /**
    * @param  int $id
    * @param  AnnouncementUpdateDTO $updateDTO
    */
    public function updateById($id,AnnouncementUpdateDTO $updateDTO)
    {
        $data = $updateDTO->toArray();
        foreach($data as &$value){
            if (is_array($value)){
                $value= json_encode(array_values($value));
            }
        }
        $data['updated_at'] = now();
        unset($data['page']);unset($data['limit']);
        $this->model->where('id',$id)->update($data);
    }

    public function deleteById($id)
    {
        $this->model->where('id',$id)->delete();
    }

    public function deleteByIds($ids)
    {
        if (empty($ids)) return;
        $this->model->whereIn('id',$ids)->delete();
    }
    public function getById($id)
    {
        return $this->model->where('id',$id)->first();
    }
}
